import React, { useState, useRef, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useLocalization } from '../hooks/useLocalization';
import { SUPPORTED_LANGS } from '../constants';
import { GlobeIcon, ChevronDownIcon } from './icons';

const LanguageSwitcher: React.FC = () => {
    const [isOpen, setIsOpen] = useState(false);
    const { language } = useLocalization();
    const navigate = useNavigate();
    const location = useLocation();
    const wrapperRef = useRef<HTMLDivElement>(null);

    const selectedLang = SUPPORTED_LANGS.find(l => l.code === language) || SUPPORTED_LANGS[0];

    const changeLanguage = (newLangCode: string) => {
        // Find the base path (the part of the path without the language code)
        let basePath = location.pathname;
        if (language !== 'en' && basePath.startsWith(`/${language}`)) {
            basePath = basePath.substring(`/${language}`.length);
        }
        // Ensure basePath starts with a '/' for root
        if (basePath === '') {
            basePath = '/';
        }

        // Construct the new path
        let newPath;
        if (newLangCode === 'en') {
            newPath = basePath;
        } else {
            // For root path, new path is just /langCode. For others, /langCode/path
            newPath = basePath === '/' ? `/${newLangCode}` : `/${newLangCode}${basePath}`;
        }
        
        navigate(newPath);
        setIsOpen(false);
    };

    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        }
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [wrapperRef]);


    return (
        <div className="relative" ref={wrapperRef}>
            <button
                onClick={() => setIsOpen(!isOpen)}
                className="flex items-center space-x-2 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
            >
                <GlobeIcon />
                <span>{selectedLang.name}</span>
                <ChevronDownIcon isOpen={isOpen} />
            </button>
            {isOpen && (
                <div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-50">
                    <div className="py-1 max-h-60 overflow-y-auto">
                        {SUPPORTED_LANGS.map(lang => (
                            <button
                                key={lang.code}
                                onClick={() => changeLanguage(lang.code)}
                                className={`w-full text-left block px-4 py-2 text-sm ${
                                    language === lang.code
                                        ? 'bg-primary text-white'
                                        : 'text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
                                }`}
                            >
                                {lang.name}
                            </button>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
};

export default LanguageSwitcher;